package com.base.util;

import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	
	static FastJsonUtil fastjson = new FastJsonUtil();
	static JacksonUtil jackson = new JacksonUtil();
	
	private static class FastJsonUtil implements JsonService {
		@Override
		public String toJsonStr(Object obj) {
			return JSON.toJSONString(obj);
		}
		@Override
		public <T> T parseObj(String json, Class<T> cls) {
			return JSON.parseObject(json, cls);
		}
	}
	
	private static class JacksonUtil implements JsonService {
		static ObjectMapper mapper = new ObjectMapper();
		@Override
		public String toJsonStr(Object obj) {
			try {
				return mapper.writeValueAsString(obj);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		}
		@Override
		public <T> T parseObj(String json, Class<T> cls) {
			try {
				return mapper.readValue(json, cls);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public interface JsonService {
		String toJsonStr(Object obj);
		<T> T parseObj(String json, Class<T> cls);
	}
	
	public enum JsonTypeEnum {
		FastJson, Jackson
	}
	
	public static JsonService use() {
		return fastjson;
	}
	
	public static JsonService use(JsonTypeEnum jsontype) {
		if(jsontype.equals(JsonTypeEnum.FastJson)) return fastjson;
		else if(jsontype.equals(JsonTypeEnum.Jackson)) return jackson;
		return fastjson;
	}
	
}
